from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List

from app.db.database import get_db
from app.core.security import get_current_user
from app.schemas.user import User, UserBrief, UserUpdate, UserWithStats
from app.crud import user as user_crud

router = APIRouter()

@router.get("/me", response_model=User)
async def read_users_me(current_user: dict = Depends(get_current_user), db: Session = Depends(get_db)):
    """获取当前用户信息"""
    user = user_crud.get_user(db, user_id=current_user["id"])
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

@router.put("/me", response_model=User)
async def update_user_me(
    user_update: UserUpdate,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新当前用户信息"""
    updated_user = user_crud.update_user(db, user_id=current_user["id"], user_update=user_update)
    if not updated_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return updated_user

@router.get("/{user_id}", response_model=UserWithStats)
async def read_user(user_id: int, db: Session = Depends(get_db)):
    """获取指定用户信息"""
    user = user_crud.get_user(db, user_id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 获取统计信息
    follower_count = len(user_crud.get_followers(db, user_id=user_id))
    following_count = len(user_crud.get_following(db, user_id=user_id))
    post_count = len(user.posts)
    
    # 创建带统计信息的用户
    user_with_stats = UserWithStats.from_orm(user)
    user_with_stats.follower_count = follower_count
    user_with_stats.following_count = following_count
    user_with_stats.post_count = post_count
    
    return user_with_stats

@router.get("/{user_id}/followers", response_model=List[UserBrief])
async def read_user_followers(user_id: int, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取用户的关注者列表"""
    user = user_crud.get_user(db, user_id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    followers = user_crud.get_followers(db, user_id=user_id, skip=skip, limit=limit)
    return followers

@router.get("/{user_id}/following", response_model=List[UserBrief])
async def read_user_following(user_id: int, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    """获取用户关注的用户列表"""
    user = user_crud.get_user(db, user_id=user_id)
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    following = user_crud.get_following(db, user_id=user_id, skip=skip, limit=limit)
    return following

@router.post("/{user_id}/follow", response_model=dict)
async def follow_user(
    user_id: int,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """关注用户"""
    if current_user["id"] == user_id:
        raise HTTPException(status_code=400, detail="不能关注自己")
    
    follow = user_crud.follow_user(db, follower_id=current_user["id"], followed_id=user_id)
    if not follow:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    return {"status": "success", "message": "关注成功"}

@router.delete("/{user_id}/follow", response_model=dict)
async def unfollow_user(
    user_id: int,
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """取消关注用户"""
    if current_user["id"] == user_id:
        raise HTTPException(status_code=400, detail="不能取消关注自己")
    
    result = user_crud.unfollow_user(db, follower_id=current_user["id"], followed_id=user_id)
    if not result:
        raise HTTPException(status_code=404, detail="未找到关注关系")
    
    return {"status": "success", "message": "取消关注成功"} 